package com.thinkfit.jy.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.AppUtils;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.manager.DataManager;
import com.common.lib.utils.BaseUtils;
import com.thinkfit.jy.R;
import com.thinkfit.jy.fragment.FreeMovementItem0Fragment;
import com.thinkfit.jy.fragment.FreeMovementItem1Fragment;
import com.thinkfit.jy.fragment.FreeMovementItem2Fragment;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.utils.ApkListViewUtils;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.DialogViewUtils;
import com.thinkfit.jy.utils.EquipmentInfoUtils;
import com.thinkfit.jy.utils.LogUtils;
import com.thinkfit.jy.utils.MotionDataUtils;
import com.thinkfit.jy.utils.SetTargetViewUtils;
import com.thinkfit.jy.utils.ShowSpeedViewUtils;
import com.thinkfit.jy.utils.SimpleSettingViewUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.thinkfit.jy.utils.SystemUtils;
import com.thinkfit.jy.utils.ThemeUtils;
import com.thinkfit.jy.utils.Utils;
import com.thinkfit.jy.view.CCTrackView;
import com.thinkfit.jy.view.CarTrackView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;

public class FreeMovementNewActivity extends MainActivity{

//    TrackView trackView;
//    CarTrackView trackView;
    CCTrackView trackView;
    ConstraintLayout clMain,clTop,clPb,clSetItem;
    TextView tvCircle,tvMeanSpeed,tvMeanPace,tvMeanStride,tvMeanStrideUnit,tvAvgStride,tvRemaining,tvRemainingUnit
            ,tvRemainingTip,tvSlop12,tvSlop9,tvSlop6,tvSlop3,tvSlopUnit,tvSpeed12,tvSpeed9,tvSpeed6,tvSpeed3,tvSpeedUnit
            ,tvArea,tvLanguage,tvUnit;
    ImageView ivHome,ivSlopReduce,ivSlopAdd,ivSpeedReduce,ivSpeedAdd,ivApk;
    ProgressBar pb;
    ViewPager sportItem;
    LinearLayout ll_dot;
    int mCurrentSportItem = 1;
    private ArrayList<BaseFragment> mFragments;
    int allTime,distance;
    int slopItem = 0;
    int speedInt = 0;
    float allSpeed;
    float allPace;
    float allStride;
    int count = 0;
    int type;
    float num;
    int max = 0;
    boolean isSpeed = false;
    boolean isTreadmill;
    boolean isSlop = false;
    boolean isLongClick = false;

    ArrayList<TextView> slopList = new ArrayList<>();
    ArrayList<Integer> slopItemList = new ArrayList<>();
    float speedf;
    protected int getLayoutId() {
        return R.layout.activity_free_movement_new;
    }

    @Override
    public void init() {
//        type = getIntent().getIntExtra(Constants.BUNDLE_EXTRA, 0);
//        num = getIntent().getIntExtra(Constants.BUNDLE_EXTRA_2, 0);
        isTreadmill = (DeviceTypeUtils.getDeviceType() == 2);
        ArrayList<Float> setTarget = DataManager.Companion.getInstance().getSetTarget();
        if(setTarget.size() > 0){
            type = Math.round(setTarget.get(0));
            num = setTarget.get(1);
            LogUtils.getInstance().l(LogUtils.HINT,"xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  type : "+type+"  num : "+num);
        }
        clMain = findViewById(R.id.cl_main);
        clTop = findViewById(R.id.cl_top);
        clPb = findViewById(R.id.cl_pb);
        pb = findViewById(R.id.pb);
        trackView = findViewById(R.id.trackView);
        tvSlop12 = findViewById(R.id.tv_slop_12);
        tvSlop9 = findViewById(R.id.tv_slop_9);
        tvSlop6 = findViewById(R.id.tv_slop_6);
        tvSlop3 = findViewById(R.id.tv_slop_3);
        tvSlopUnit = findViewById(R.id.tv_slop_unit);
        tvSpeed12 = findViewById(R.id.tv_speed_12);
        tvSpeed9 = findViewById(R.id.tv_speed_9);
        tvSpeed6 = findViewById(R.id.tv_speed_6);
        tvSpeed3 = findViewById(R.id.tv_speed_3);
        tvSpeedUnit = findViewById(R.id.tv_speed_unit);

        tvCircle = findViewById(R.id.tv_circle);
        tvMeanSpeed = findViewById(R.id.tv_mean_speed);
        tvMeanPace = findViewById(R.id.tv_mean_pace);
        tvMeanStride = findViewById(R.id.tv_mean_stride);
        tvMeanStrideUnit = findViewById(R.id.tv_mean_stride_unit);
        tvAvgStride = findViewById(R.id.tv_avg_stride);
        tvRemaining = findViewById(R.id.tv_remaining);
        tvRemainingUnit = findViewById(R.id.tv_remaining_unit);
        tvRemainingTip = findViewById(R.id.tv_remaining_tip);
        sportItem = findViewById(R.id.fl_sport_item);
        ll_dot = findViewById(R.id.ll_dot);
        clSetItem = findViewById(R.id.cl_set_item);

        tvArea = findViewById(R.id.tv_area);
        tvLanguage = findViewById(R.id.tv_language);
        tvUnit = findViewById(R.id.tv_unit);

        initViewPager();
        initView();
        if(type != 0){
//            clPb.setVisibility(View.VISIBLE);
            clTop.setVisibility(View.INVISIBLE);
            if(type == SetTargetViewUtils.TYPE_TIME){
                max = Math.round(num*60f);
                tvRemainingUnit.setVisibility(View.GONE);
            }else if(type == SetTargetViewUtils.TYPE_DISTANCE){
                max = Math.round(num*1000f);
                tvRemainingUnit.setVisibility(View.VISIBLE);
                tvRemainingUnit.setText(getString(R.string.app_km));
            }else if(type == SetTargetViewUtils.TYPE_KCAL){
                max = Math.round(num*10f);
                tvRemainingUnit.setVisibility(View.VISIBLE);
                tvRemainingUnit.setText(getString(R.string.app_kcal));
            }
            pb.setMax(max);
        }else {
            clPb.setVisibility(View.INVISIBLE);
            clTop.setVisibility(View.VISIBLE);
        }

        tvSlop12.setOnClickListener(this);
        tvSlop9.setOnClickListener(this);
        tvSlop6.setOnClickListener(this);
        tvSlop3.setOnClickListener(this);
        slopList.add(tvSlop12);
        slopList.add(tvSlop9);
        slopList.add(tvSlop6);
        slopList.add(tvSlop3);

        if(!isTreadmill){
            tvSpeed12.setText("-");
            tvSpeed9.setText("-");
            tvSpeed6.setText("-");
            tvSpeed3.setText("-");
            tvSpeedUnit.setText("-");
            tvSpeed12.setOnClickListener(this);
            tvSpeed9.setOnClickListener(this);
            tvSpeed6.setOnClickListener(this);
            tvSpeed3.setOnClickListener(this);
        }
        clSetItem.setOnClickListener(this);

        Utils.initRegion(tvArea,tvLanguage,tvUnit);
        initSlop();
    }

    public void initSlop(){
        int slop = EquipmentInfoUtils.getInstance().getSlop();
        int item = slop/slopList.size();
        for (int i = 0; i < slopList.size(); i++){
            int level = slop - item * i;
            slopItemList.add(level);
            slopList.get(i).setText(level+"");
        }

    }

    public void initView(){
        if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)){
            tvMeanStrideUnit.setText(getString(R.string.app_spm));
            tvAvgStride.setText(getString(R.string.app_free_avg_stride));
        }else if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.SPINNING)
                || MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.ELLIPTICAL_MACHINE)){
            tvMeanStrideUnit.setText(getString(R.string.app_rpm));
            tvAvgStride.setText(getString(R.string.app_free_avg_cadence));
        }else if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
            tvMeanStrideUnit.setText(getString(R.string.app_spm));
            tvAvgStride.setText(getString(R.string.app_free_avg_stroke));
        }
//        trackView.setVisibility(View.INVISIBLE);
    }

    public void initViewPager(){
        if(mFragments == null){
            mFragments = new ArrayList<>();
        }else {
            mFragments.clear();
        }
//        mFragments.add(FreeMovementItem2Fragment.getInstance(type,num));
        mFragments.add(FreeMovementItem2Fragment.getInstance(type,num));
        mFragments.add(FreeMovementItem0Fragment.getInstance(type,num));
        mFragments.add(FreeMovementItem1Fragment.getInstance(type,num));

        for (int i = 0; i < mFragments.size(); i++) {
            View inflate = LayoutInflater.from(getContext()).inflate(R.layout.view_dot, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
            layoutParams.weight = 1;
            inflate.setLayoutParams(layoutParams);
            ll_dot.addView(inflate);
        }

//        sportItem.setOffscreenPageLimit(0);
        sportItem.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }

        });
        sportItem.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                ll_dot.getChildAt(mCurrentSportItem).findViewById(R.id.v_dot).setBackgroundResource(R.drawable.dot_normal);
                ll_dot.getChildAt(position).findViewById(R.id.v_dot).setBackgroundResource(R.drawable.dot_selected);
                mCurrentSportItem = position;
//                if(mCurrentSportItem == 0){
//                    tvStartSports.setVisibility(View.VISIBLE);
//                }else {
//                    tvStartSports.setVisibility(View.GONE);
//                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        sportItem.setCurrentItem(mCurrentSportItem);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
//            case R.id.iv_home:
//                if(MotionDataUtils.getInstance().isRun()){
//                    if(MotionDataUtils.getInstance().isRun()||MotionDataUtils.getInstance().isPause()){
//                        DialogViewUtils.getInstance().initView(getContext(),true,DialogViewUtils.EXIT_SPORT);
//                        return;
//                    }
//                }
//                Log.e("aaaaaaaaaaaaa", "ivHome");
//                if(!SystemUtils.isForeground(getContext(),getPackageName())){
//                    //TODO 在第三方应用是显示的是返回按钮
//                }else {
//                    Intent intent = new Intent(getContext(),MainActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    startActivity(intent);
//                }
////                BackButtonViewUtils.getInstance().closeButton();//去除控件
//                ApkListViewUtils.getInstance().backHome();
//
//                break;
//            case R.id.tv_stop:
//                DialogViewUtils.getInstance().initView(getContext(),true,DialogViewUtils.EXIT_SPORT);
//                break;
//            case R.id.tv_pause:
//                if(EquipmentInfoUtils.getInstance().isPause()){
//                    if(DeviceTypeUtils.connectDeviceType() == 0){
//                        if(MotionDataUtils.getInstance().isPause()){
//                            initSpeedSlopEnabled(true);
//                            BluetoothOrder.getInstance().startTreadmill();
//                        }else {
//                            initSpeedSlopEnabled(false);
//                            pauseDevice();
//                        }
//                    }else {
//                        if(MotionDataUtils.getInstance().isPause()){
//                            initSpeedSlopEnabled(true);
//                            SerialPortManager.getInstance().reStartRun();
//                        }else {
//                            initSpeedSlopEnabled(false);
//                            pauseDevice();
//                        }
//                    }
//
//                }else {
//                    DialogViewUtils.getInstance().initView(getContext(),false,DialogViewUtils.EXIT_SPORT);
////                    tvSetGoal.setText(mContext.getString(R.string.app_set_goal));
////                    mType = 0;
////                    mNum = 0;
//                }
//
//                break;
//            case R.id.iv_slop_reduce:
//                isLongClick = false;
//                resetSlop(false);
//                break;
//            case R.id.iv_slop_add:
//                isLongClick = false;
//                resetSlop(true);
//                break;
//            case R.id.iv_speed_reduce:
//                isLongClick = false;
//                resetSpeed(false);
//                break;
//            case R.id.iv_speed_add:
//                isLongClick = false;
//                resetSpeed(true);
//                break;
            case R.id.tv_slop_12:
                slopItem = slopItemList.get(0);
                setSlop(slopItem);
                break;
            case R.id.tv_slop_9:
                slopItem = slopItemList.get(1);
                setSlop(slopItem);
                break;
            case R.id.tv_slop_6:
                slopItem = slopItemList.get(2);
                setSlop(slopItem);
                break;
            case R.id.tv_slop_3:
                slopItem = slopItemList.get(3);
                setSlop(slopItem);
                break;
            case R.id.tv_speed_12:
                speedInt = 120;
                setSpeed(speedInt);
                break;
            case R.id.tv_speed_9:
                speedInt = 90;
                setSpeed(speedInt);
                break;
            case R.id.tv_speed_6:
                speedInt = 60;
                setSpeed(speedInt);
                break;
            case R.id.tv_speed_3:
                speedInt = 30;
                setSpeed(speedInt);
                break;
            case R.id.cl_set_item:
                SimpleSettingViewUtils.getInstance().initView(getContext(),this);
                break;
//            case R.id.iv_apk:
//                if(appPopupWindow == null){
////                    setImage(R.id.iv_app,R.drawable.img_app_open);
//                    appPopupWindow = new AppPopupWindow(getContext(), getAppList(), new AppPopupWindow.OnDismiss() {
//                        @Override
//                        public void onDismiss() {
//                            appPopupWindow = null;
////                            setImage(R.id.iv_app,R.drawable.img_app);
//                        }
//                    });
//                    appPopupWindow.show(this);
//                }else {
////                    setImage(R.id.iv_app,R.drawable.img_app);
//                    appPopupWindow.dismiss();
//                }
//                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.getInstance().l(LogUtils.HINT,("CurrentActivity"+this.getClass().getSimpleName()));

        SportsStatusBarViewUtils.getInstance().initView(getApplicationContext());
        ShowSpeedViewUtils.getInstance().goneLayout();
        clMain.setBackgroundResource(ThemeUtils.getInstance().getMainTheme());
//        ShowSpeedViewUtils.getInstance().isOnClick(false);
//        SportsStatusBarViewUtils.getInstance().isMain(true);
        SportsStatusBarViewUtils.getInstance().setHomeView(false);
        initSound();
    }

    @Override
    protected void onStop() {
        super.onStop();
        ShowSpeedViewUtils.getInstance().isOnClick(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        super.onReceive(map);
        if (map.containsKey(EventBusEvent.STOP_RUN)) {
            System.out.println("BluetoothOrder ------------->  STOP_RUN : 2222");
//            showStartBtn(false);
            BluetoothOrder.getInstance().uploadSportInfo(true);
            initWidget();
        }else if(map.containsKey(EventBusEvent.KILL_ACTIVITY)){
//            HashMap<String, Object> map1 = new HashMap<>();
//            map1.put(EventBusEvent.STOP_RUN,"");
//            EventBus.getDefault().post(map1);
            finish();
        }else if(map.containsKey(EventBusEvent.VOICE_CHANGE)){
            int i = (int) map.get(EventBusEvent.VOICE_CHANGE);
            if(i <= 0){
                setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_off);

            }else {
                setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_max);
            }
//            SportsStatusBarViewUtils.getInstance().setVolume((int) map.get(EventBusEvent.VOICE_CHANGE));
        }

    }

    public void initSound(){
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        if(currentVolume <= 0){
            setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_off);

        }else {
            setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_max);
        }
    }

    @Override
    public void resetInfo(SerialPortManager.CurrentInfo info) {
        if(MotionDataUtils.getInstance().isRun()){

            if(allTime == info.time){
                return;
            }
            allTime = info.time;
            count ++;
            double num = Math.floor(info.distance / 400);
            long round = Math.round(num);
            if(round > 1){
                tvCircle.setText(getString(R.string.app_free_laps,round+""));
            }else {
                tvCircle.setText(getString(R.string.app_free_lap,round+""));
            }
            float speed = 0f;

            if(DeviceTypeUtils.getDeviceType() == 2){
                speed = info.speed*0.1f;
            }else {
                speed = info.speed*0.01f;
            }
//            if(distance == info.distance){
//
//            }else {
////                trackView.changeDistance(info.distance);
//                trackView.setCursorPosition(info.distance);
//                distance = info.distance;
//            }

//            trackView1.setPosition(Float.valueOf(info.distance));
//            allSpeed = allSpeed +speed;

//            float speeds = (info.distance * 1000)/ allTime;
//            allSpeed = speeds*3.6f;


//            if(allSpeed<=0){
//                allSpeed = 0;
//            }
//            allStride = allStride+(info.count/info.time)*60;

//            tvMeanSpeed.setText(Utils.getNewFloat2(allSpeed/count));


            String text;
            if ((info.distance/ 1000f) <= 0) {
                text = "00:00";
            } else {
                int time = (int) (allTime /(info.distance / 1000f));  //计算好了配速   //((info.time == 0 || info.distance < 10) ? 0 : (int) (500 / (info.distance * 1.0f / info.time) + 0.5f));//计算500需要多少秒
                int hour = time / 3600;
                int minute = (time / 60) % 60;
                int second = time % 60;
                if (hour > 0) {
                    text = BaseUtils.StaticParams.getNewText(hour) + ":"
                            + BaseUtils.StaticParams.getNewText(minute) + "'"
                            + BaseUtils.StaticParams.getNewText(second)+"''";
                } else {
                    text = BaseUtils.StaticParams.getNewText(minute) + "'"
                            + BaseUtils.StaticParams.getNewText(second)+"''";
                }
            }
            if(type == SetTargetViewUtils.TYPE_TIME){
                pb.setProgress(info.time);
                tvRemaining.setText(remainNum(info.time));
            }else if(type == SetTargetViewUtils.TYPE_DISTANCE){
                pb.setProgress(info.distance);
                tvRemaining.setText(remainNum(info.distance));
            }else if(type == SetTargetViewUtils.TYPE_KCAL){
                pb.setProgress(info.kcal);
                tvRemaining.setText(remainNum(info.kcal));
            }


//            tvMeanPace.setText(text);

//            if(DeviceTypeUtils.getDeviceType() == 2 ||DeviceTypeUtils.getDeviceType() == 5){
//                double rand = Math.random()*10;
//                rand=(rand-5)*0.01+1;
//                int rpm = (int) Math.ceil(speed*60/3.6*rand);
//                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    rpm  : "+rpm);
//                tvMeanStride.setText(rpm+"");
//            }else {
//                tvMeanStride.setText(info.rpm+"");
//            }

        }
    }



    public String remainNum(int num){
        String str = null;
        if(type == SetTargetViewUtils.TYPE_TIME){
            int time = max - num;
            if(time <= 0){
                str = getString(R.string.app_target_complete);
                tvRemainingTip.setVisibility(View.INVISIBLE);
            }else {
                int hour = time / 3600;
                int minute = (time / 60) % 60;
                int second = time % 60;
                if (hour > 0) {
                    str = BaseUtils.StaticParams.getNewText(hour) + ":"
                            + BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second);
                } else {
                    str = BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second);
                }
            }

        }else if(type == SetTargetViewUtils.TYPE_DISTANCE){
            int distance = max - num;
            if(distance <= 0){
                str = getString(R.string.app_target_complete);
                tvRemainingTip.setVisibility(View.INVISIBLE);
            }else {
                str = Utils.getNewFloat2(distance / 1000f);
            }


        }else if(type == SetTargetViewUtils.TYPE_KCAL){
            int kcal = max - num;
            if(kcal <= 0){
                str = getString(R.string.app_target_complete);
                tvRemainingTip.setVisibility(View.INVISIBLE);
            }else {
                str = Utils.getNewFloat(kcal / 10f);
            }

        }
        return str;
    }
    private void setSpeed(int speed){
        int slop = MotionDataUtils.getInstance().getCurrentInfo().slop;
        if(DeviceTypeUtils.connectDeviceType() == 0){
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  speed : "+speed);
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  speed   speedInt: "+speed);
            if(DeviceTypeUtils.getInstance().isTreadmill()){
                BluetoothOrder.getInstance().setTreadmillSpeedAndSlope(speed,slop);
            }else {
                BluetoothOrder.getInstance().setNowelAndSlope(speed,slop);
            }
        }else {
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  speed11111 : "+speed);
            SerialPortManager.getInstance().setSpeedSlop(speed, slop);
        }
    }

    public void setSlop(int slop){
//        int speed = MotionDataUtils.getInstance().getCurrentInfo().speed;
        int speed = MotionDataUtils.getInstance().deviceSpeed;
        if(DeviceTypeUtils.connectDeviceType() == 0){
            if (MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)){
                if (slop < 0) {
                    return;
                }
                BluetoothOrder.getInstance().setTreadmillSpeedAndSlope(speed,slop);

            }else {

                if (slop < 0 || slop > 32) {
                    return;
                }
                int slopNum = MotionDataUtils.getInstance().getCurrentInfo().slop;
                BluetoothOrder.getInstance().setNowelAndSlope(slop, slopNum);
            }
        }else {
            if (MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)) {
                if (slop < 0) {
                    return;
                }
                System.out.println("ddddddddddddddddddddddd    sendMsg1111 :  slop : "+slop+"   speed : "+speed);
                SerialPortManager.getInstance().setSpeedSlop(speed, slop);
            } else {
                if (slop < 0 || slop > 32) {
                    return;
                }
                System.out.println("ddddddddddddddddddddddd    sendMsg2222 :  slop : "+slop);
                int slopNum = MotionDataUtils.getInstance().getCurrentInfo().slop;
                SerialPortManager.getInstance().setResistanceSlop(slop, slopNum);
            }
        }
    }

    public void pauseDevice(){
        if(!(SerialPortManager.getInstance().isConnected() || BluetoothOrder.getInstance().isConnect())){
            System.out.println("ddddddddddddddddddddddd   未连接设备");
            return;
        }
        if(DeviceTypeUtils.connectDeviceType() == 0){//判断连接类型
            BluetoothOrder.getInstance().closeRxJavaClone();
            BluetoothOrder.getInstance().closeTreadmillStateDisposable();
            if(EquipmentInfoUtils.getInstance().isPause()){
                System.out.println("ddddddddddddddddddddddd   蓝牙通知设备暂停");
                if(DeviceTypeUtils.getInstance().isTreadmill()){
                    BluetoothOrder.getInstance().pauseTreadmill();
                }else {
                    BluetoothOrder.getInstance().bluetoothOrderWrite(BluetoothOrder.EQUIPMENT_PAUSE);
                }

            }

        }else {
            System.out.println("ddddddddddddddddddddddd   串口通知设备暂停");
            SerialPortManager.getInstance().pauseRun();
        }
    }

    public ArrayList<AppUtils.AppInfo> getAppList(){
        ArrayList<AppUtils.AppInfo> list1 = new ArrayList<>();
        PackageManager pm = this.getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        int size = packages.size();
        for (int i = 0; i < size; i++) {
            PackageInfo packageInfo = packages.get(i);
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0 ||
                    packageInfo.packageName.equals(this.getPackageName())) {
                continue;
            }
            list1.add(new AppUtils.AppInfo(
                    packageInfo.packageName,
                    packageInfo.applicationInfo.loadLabel(pm).toString(),
                    packageInfo.applicationInfo.loadIcon(pm),
                    "",
                    packageInfo.versionName,
                    packageInfo.versionCode,
                    false
            ));
        }
        return list1;
    }

    public void initWidget(){
        tvMeanSpeed.setText("0.0");
        tvMeanPace.setText("0'00''");
        tvMeanStride.setText(0+"");
        tvCircle.setText(getString(R.string.app_free_lap,0+""));
        distance = 0;
    }

    public void initSpeedSlopEnabled(boolean b){
        ivSpeedAdd.setEnabled(b);
        ivSpeedReduce.setEnabled(b);
        ivSlopAdd.setEnabled(b);
        ivSlopReduce.setEnabled(b);
    }

    public String speedKmMin(int speed){
        String text;
        if (speed <= 0) {
            text = "00’00’’";
        }else {
            int time = (int) (60 / (speed * 0.01) + 1);  //计算好了配速   //((info.time == 0 || info.distance < 10) ? 0 : (int) (500 / (info.distance * 1.0f / info.time) + 0.5f));//计算500需要多少秒
            int hour = time / 3600;
            int minute = (time / 60) % 60;
            int second = time % 60;
            if (hour > 0) {
                text = BaseUtils.StaticParams.getNewText(hour) + "’"
                        + BaseUtils.StaticParams.getNewText(minute) + "’’"
                        + BaseUtils.StaticParams.getNewText(second)+ "’’";
            } else {
                text = BaseUtils.StaticParams.getNewText(minute) + "’"
                        + BaseUtils.StaticParams.getNewText(second)+ "’’";
            }
        }
        return text;
    }
}
